package xyz.lwm.lazycat.transaction.policy;

import xyz.lwm.lazycat.transaction.execute.TranDefinition;
import xyz.lwm.lazycat.transaction.execute.Transaction;
import xyz.lwm.lazycat.transaction.execute.TransactionManager;

/**
 * 如果存在当前事务，则在嵌套事务中执行, 否则同 REQUIRED, 创建新事务; <br>
 * 嵌套事务异常时，将回滚嵌套事务，并继续外层事务; <br>
 * 外层事务异常时，将回滚当前及所有嵌套事务.
 *
 * @author lwm
 * @see xyz.lwm.lazycat.transaction.execute.Propagation#NESTED
 */
class NestedPolicy extends AbstractPolicy {

    public NestedPolicy(TranDefinition tranDefinition) {
        super(tranDefinition);
    }

    @Override
    public <T> T execute(CheckedSupplier<T> supplier) throws Throwable {
        Transaction current = TransactionManager.current();
        // 当前事务开启，则嵌套事务; 否则同 REQUIRED
        return new RequiresNewPolicy(tranDefinition, current).execute(supplier);
    }

}
